
"""
    角色
"""

from rest_framework.views import APIView
from utils.json_response import JsonResponse
from utils.model_view_set import CustomModelViewSet
from users.models import Role, Organization
from users.serialiaers import role


class OrganizationRoleTreeView(APIView):
    """
    组织架构关联角色树
    """
    def get(self, request):
        organizations = Organization.objects.all()
        serializer = role.OrganizationRoleTreeSerializer(organizations, many=True)
        tree_dict = {}
        tree_data = []
        for item in serializer.data:
            new_item = {
                'id': item['id'],
                'label': item['label'],
                'pid': item['pid'],
                'children': item['children']
            }
            tree_dict[item['id']] = new_item
        for i in tree_dict:
            if tree_dict[i]['pid']:
                pid = tree_dict[i]['pid']
                parent = tree_dict[pid]
                parent['children'].append(tree_dict[i])
            else:
                tree_data.append(tree_dict[i])
        return JsonResponse(data=tree_data, code=200)


class RoleModelView(CustomModelViewSet):
    """
    角色管理：增删改查导
    """
    perms_map = ({'*': 'admin'}, {'*': 'role_all'}, {'get': 'role_list'}, {'post': 'role_create'}, {'put': 'role_edit'},
                 {'delete': 'role_delete'}, {'export': 'role_export'})
    queryset = Role.objects.all().exclude(id=1)
    serializer_class = role.RoleModelSerializer
    search_fields = ('name', 'desc')
    ordering_fields = ('id',)

    sheet = '角色表'
    title = {'id': 'ID', 'name': '角色名', 'department': '所属组织', 'desc': '描述'}

    def get_serializer_class(self):
        if self.action == 'list':
            return role.RoleModelListSerializer
        elif self.action == 'retrieve':
            return role.RoleModelRetrieveViewSerializer
        elif self.action == 'export_current' or self.action == 'export_all':
            return role.RoleModelExportSerializer
        return role.RoleModelSerializer
